package com.robotics

import com.cloudbees.plugins.credentials.CredentialsMatchers
import com.cloudbees.plugins.credentials.CredentialsProvider
import com.cloudbees.plugins.credentials.common.StandardCredentials
import com.cloudbees.plugins.credentials.common.StandardListBoxModel
import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials
import edu.umd.cs.findbugs.annotations.CheckForNull
import hudson.EnvVars
import hudson.Extension
import hudson.Util
import hudson.model.*
import hudson.model.queue.Tasks
import hudson.plugins.git.*
import hudson.security.ACL
import hudson.util.FormValidation
import hudson.util.ListBoxModel
import jenkins.model.Jenkins
import jenkins.security.FIPS140
import org.apache.commons.lang.StringUtils
import org.eclipse.jgit.lib.Config
import org.eclipse.jgit.lib.ObjectId
import org.eclipse.jgit.transport.RemoteConfig
import org.jenkinsci.plugins.gitclient.Git
import org.jenkinsci.plugins.gitclient.GitClient
import org.jenkinsci.plugins.gitclient.GitURIRequirementsBuilder

class GitUtils {

    def  getGitClient(String jobName, String url, String credentialId) {
        EnvVars environment
        Jenkins jenkins = Jenkins.get()
        Computer computer = jenkins.toComputer()
        environment = computer == null ? new EnvVars() : computer.buildEnvironment(TaskListener.NULL)

        GitClient git = Git.with(TaskListener.NULL, environment)
                    .using(GitTool.getDefaultInstallation().getGitExe())
                    .getClient()
        Item project = jenkins.getItem(jobName)
        StandardCredentials credential = CredentialsMatchers.firstOrNull(
                    CredentialsProvider.lookupCredentialsInItem(StandardCredentials.class, project, ACL.SYSTEM2,
                            GitURIRequirementsBuilder.fromUri(url).build()),
                    CredentialsMatchers.withId(credentialId))

        git.clearCredentials()
        git.addCredentials(url, credential)
        git.addDefaultCredentials(credential)
        return git
    }

    // 根据项目名称、url、获取对应的tag
    def getRemoteTags(String jobName, String url, String credentialId) {
        def tags = []
        def git = getGitClient(jobName, url, credentialId)
        def  branchs = git.getRemoteReferences(url, 'refs/heads/*', false, false)
        def release_tags = git.getRemoteReferences(url, 'refs/tags/*', false, false)

        for ( branch in branchs.keySet()) {
            def item = [:]
            def tag = branch.replace('refs/heads/', '')
            def fruits = tag.split('_')
            item['branch'] = tag
            item['isTag'] = false
            String commitId = branchs[branch].getName()
            item['commitId'] =  commitId
            if ((tag.indexOf('ci_') == 0 || tag.indexOf('last_ci_') == 0) && fruits.length > 2) {
                def versions = fruits[2].split('\\.')
                item['mainVersion'] = versions.length > 0 ? versions[0] : '0'
                item['minorVersion'] = versions.length > 1 ? versions[1] : '0'
                item['stageVersion'] = versions.length > 2 ? versions[2] : '0'
                item['patchVersion'] = versions.length > 3 ? versions[3] : '0'
                item['greekVersion'] = fruits[1]
                item['labelVersion'] = fruits.length > 3 ? fruits[3] : ''
            }else {
                item['mainVersion'] = ' '
                item['minorVersion'] = ' '
                item['stageVersion'] = ' '
                item['patchVersion'] = ' '
                item['greekVersion'] = 'beta'
            }
            tags << item
        }
        for ( branch in release_tags.keySet()) {
            def item = [:]
            def tag = branch.replace('refs/tags/', '')
            def fruits = tag.split('_')
            item['branch'] = tag
            item['isTag'] = true
            String commitId = release_tags[branch].getName()
            item['commitId'] =  commitId
            if ((tag.indexOf('ci_') == 0 || tag.indexOf('last_ci_') == 0) && fruits.length > 2) {
                def versions = fruits[2].split('\\.')
                item['mainVersion'] = versions.length > 0 ? versions[0] : '0'
                item['minorVersion'] = versions.length > 1 ? versions[1] : '0'
                item['stageVersion'] = versions.length > 2 ? versions[2] : '0'
                item['patchVersion'] = versions.length > 3 ? versions[3] : '0'
                item['greekVersion'] = fruits[1]
                item['labelVersion'] = fruits.length > 3 ? fruits[3] : ''
            }else {
                item['mainVersion'] = ' '
                item['minorVersion'] = ' '
                item['stageVersion'] = ' '
                item['patchVersion'] = ' '
                item['greekVersion'] = 'beta'
            }
            tags << item
        }
        return tags
    }

    def getBuildTag(String jobName, String url, String credentialId, String defaultTag) {
        def  tags = getRemoteTags(jobName, url, credentialId)
        def res = [:]
        if (defaultTag != null) {
            for ( tag in tags) {
                if (tag['branch'] == defaultTag) {
                    res['tag'] = tag
                    break
                }
            }
            res['tags'] = tags
            return res
        }
        for ( tag in tags) {
            if (tag['branch'].indexOf('ci_') == 0) {
                res['tag'] = tag
                res['tags'] = tags
                return res
            }
        }
        for ( tag in tags) {
            if (tag['branch'].indexOf('last_ci_') == 0) {
                res['tag'] = tag
                res['tags'] = tags
                return res
            }
        }
        res['tags'] = tags
        return res
    }

    def changTag(String jobName, String url, String credentialId, String tagName, String commitId) {
        def git = getGitClient(jobName, url, credentialId)
        git.tag(tagName, commitId)
    }
    def deleteTag(String jobName, String url, String credentialId, String tagName) {
        def git = getGitClient(jobName, url, credentialId)
        git.deleteTag(tagName)
    }

}
